<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="这里我做的这份笔记的意义仅仅是记录下自己学习Spring的历程，既不是对官方API的深入解释，也不一定是对新手友好的、知识点详尽的一份学习清单。   1 Spring IoC容器和Bean简介1.5 Bean的作用域1.5.1 介绍Spring框架支持六个作用域，但是后面四个只在web环境下才支持。重点讲单例和原型。  singleton单例。IOC容器中只有一个实例。 prototype原型">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口）">
<meta property="og:url" content="http://example.com/2021/07/05/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B02%20%20%E2%80%94%E2%80%94%20%20IOC%E5%AE%B9%E5%99%A8%202%20%EF%BC%88Bean%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F%E3%80%81%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3%EF%BC%89/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="这里我做的这份笔记的意义仅仅是记录下自己学习Spring的历程，既不是对官方API的深入解释，也不一定是对新手友好的、知识点详尽的一份学习清单。   1 Spring IoC容器和Bean简介1.5 Bean的作用域1.5.1 介绍Spring框架支持六个作用域，但是后面四个只在web环境下才支持。重点讲单例和原型。  singleton单例。IOC容器中只有一个实例。 prototype原型">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-07-04T16:00:00.000Z">
<meta property="article:modified_time" content="2021-10-14T16:41:11.657Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="Spring核心">
<meta property="article:tag" content="JavaEE">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/07/05/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B02%20%20%E2%80%94%E2%80%94%20%20IOC%E5%AE%B9%E5%99%A8%202%20%EF%BC%88Bean%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F%E3%80%81%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3%EF%BC%89/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/07/05/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B02%20%20%E2%80%94%E2%80%94%20%20IOC%E5%AE%B9%E5%99%A8%202%20%EF%BC%88Bean%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F%E3%80%81%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3%EF%BC%89/","path":"2021/07/05/Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口）/","title":"Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口）"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口） | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-Spring-IoC%E5%AE%B9%E5%99%A8%E5%92%8CBean%E7%AE%80%E4%BB%8B"><span class="nav-number">1.</span> <span class="nav-text">1 Spring IoC容器和Bean简介</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-5-Bean%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F"><span class="nav-number">1.1.</span> <span class="nav-text">1.5 Bean的作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-1-%E4%BB%8B%E7%BB%8D"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.5.1 介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-2-%E5%8D%95%E4%BE%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">1.1.2.</span> <span class="nav-text">1.5.2 单例与原型的区别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-3-%E5%8D%95%E4%BE%8B%E4%B8%8E%E5%8E%9F%E5%9E%8B%E7%9A%84%E5%9B%9B%E7%A7%8D%E4%BE%9D%E8%B5%96%E5%85%B3%E7%B3%BB"><span class="nav-number">1.1.3.</span> <span class="nav-text">1.5.3 单例与原型的四种依赖关系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-4-%E4%BD%BF%E7%94%A8%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8C%83%E5%9B%B4"><span class="nav-number">1.1.4.</span> <span class="nav-text">1.5.4. 使用自定义范围</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-6-%E8%87%AA%E5%AE%9A%E4%B9%89Bean%E7%9A%84%E6%80%A7%E8%B4%A8"><span class="nav-number">1.2.</span> <span class="nav-text">1.6 自定义Bean的性质</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-6-1-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83"><span class="nav-number">1.2.1.</span> <span class="nav-text">1.6.1 生命周期回调</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-6-1-1-%E5%88%9D%E5%A7%8B%E5%8C%96%E5%9B%9E%E8%B0%83"><span class="nav-number">1.2.1.1.</span> <span class="nav-text">1.6.1.1 初始化回调</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-6-1-2-%E9%94%80%E6%AF%81%E5%9B%9E%E8%B0%83"><span class="nav-number">1.2.1.2.</span> <span class="nav-text">1.6.1.2 销毁回调</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-6-1-3-%E9%BB%98%E8%AE%A4%E5%88%9D%E5%A7%8B%E5%8C%96%E5%92%8C%E9%94%80%E6%AF%81%E2%80%8B%E2%80%8B%E6%96%B9%E6%B3%95"><span class="nav-number">1.2.1.3.</span> <span class="nav-text">1.6.1.3 默认初始化和销毁​​方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-6-1-4-%E9%85%8D%E7%BD%AE%E5%A4%9A%E4%B8%AA%E5%9B%9E%E8%B0%83%E6%96%B9%E6%B3%95%E7%9A%84%E8%B0%83%E7%94%A8%E9%A1%BA%E5%BA%8F"><span class="nav-number">1.2.1.4.</span> <span class="nav-text">1.6.1.4 配置多个回调方法的调用顺序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-6-1-5-Lifecycle%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.2.1.5.</span> <span class="nav-text">1.6.1.5 Lifecycle接口</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-6-2-ApplicationContextAware-%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.2.2.</span> <span class="nav-text">1.6.2 ApplicationContextAware 接口</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-6-3-%E5%85%B6%E4%BB%96-Aware-%E6%8E%A5%E5%8F%A3"><span class="nav-number">1.2.3.</span> <span class="nav-text">1.6.3 其他 Aware 接口</span></a></li></ol></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/07/05/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B02%20%20%E2%80%94%E2%80%94%20%20IOC%E5%AE%B9%E5%99%A8%202%20%EF%BC%88Bean%E7%9A%84%E4%BD%9C%E7%94%A8%E5%9F%9F%E3%80%81%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%9E%E8%B0%83%E6%8E%A5%E5%8F%A3%EF%BC%89/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口） | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring 学习笔记2  ——  IOC容器 2 （Bean的作用域、生命周期回调接口）
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-07-05 00:00:00" itemprop="dateCreated datePublished" datetime="2021-07-05T00:00:00+08:00">2021-07-05</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-10-15 00:41:11" itemprop="dateModified" datetime="2021-10-15T00:41:11+08:00">2021-10-15</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Spring/" itemprop="url" rel="index"><span itemprop="name">Spring</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <blockquote>
<blockquote>
<p>这里我做的这份笔记的意义仅仅是记录下自己学习Spring的历程，既不是对官方API的深入解释，也不一定是对新手友好的、知识点详尽的一份学习清单。</p>
</blockquote>
</blockquote>
<h1 id="1-Spring-IoC容器和Bean简介"><a href="#1-Spring-IoC容器和Bean简介" class="headerlink" title="1 Spring IoC容器和Bean简介"></a>1 Spring IoC容器和Bean简介</h1><h2 id="1-5-Bean的作用域"><a href="#1-5-Bean的作用域" class="headerlink" title="1.5 Bean的作用域"></a>1.5 Bean的作用域</h2><h3 id="1-5-1-介绍"><a href="#1-5-1-介绍" class="headerlink" title="1.5.1 介绍"></a>1.5.1 介绍</h3><p>Spring框架支持六个作用域，但是后面四个只在web环境下才支持。<br>重点讲<strong>单例</strong>和<strong>原型</strong>。</p>
<ul>
<li>singleton<br>单例。IOC容器中只有一个实例。</li>
<li>prototype<br>原型。在每次请求该特定Bean时创建一个新的Bean实例。</li>
<li>request</li>
<li>session</li>
<li>application</li>
<li>websocket</li>
</ul>
<p>XML配置Bean举例。<br><strong>单例</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;accountService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.something.DefaultAccountService&quot;</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">&lt;!-- the following is equivalent, though redundant (singleton scope is the default) --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;accountService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.something.DefaultAccountService&quot;</span> <span class="attr">scope</span>=<span class="string">&quot;singleton&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>原型</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;accountService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.something.DefaultAccountService&quot;</span> <span class="attr">scope</span>=<span class="string">&quot;prototype&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="1-5-2-单例与原型的区别"><a href="#1-5-2-单例与原型的区别" class="headerlink" title="1.5.2 单例与原型的区别"></a>1.5.2 单例与原型的区别</h3><p>原型作用域用于有状态的Bean。<br>将单例作用域用于无状态的Bean。</p>
<p>单例Bean好处是无需维护会话状态，可重复复用，开销低。<br>原型作用域用于有状态的Bean，某种程度上可以当成是 new 的替代。</p>
<p>关于原型bean的生命周期管理</p>
<blockquote>
<p>与其他作用域相比，<strong>Spring不能管理原型Bean的完整生命周期</strong>。容器将实例化，配置或组装原型对象，然后将其交给客户端，而无需对该原型实例的进一步记录。因此，尽管在不考虑范围的情况下在所有对象上都调用了初始化生命周期回调方法，但<strong>在原型的情况下，不会调用已配置的销毁生命周期回调</strong>。客户端代码必须清除原型作用域内的对象并释放原型Bean拥有的昂贵资源。为了使Spring容器释放原型作用下的bean所拥有的资源，请尝试使用 bean post-processor ，其中包含对需要清理的bean的引用。</p>
</blockquote>
<h3 id="1-5-3-单例与原型的四种依赖关系"><a href="#1-5-3-单例与原型的四种依赖关系" class="headerlink" title="1.5.3 单例与原型的四种依赖关系"></a>1.5.3 单例与原型的四种依赖关系</h3><ol>
<li><p>单例依赖单例<br>这也是默认的依赖关系。没什么好说的。</p>
</li>
<li><p>原型依赖原型</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Scope(&quot;prototype&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">MyPrototype</span> &#123;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    AnotherPrototype anotherPrototype;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    MySingleton mySingleton;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Scope(&quot;prototype&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AnotherPrototype</span> &#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如上面，这样做也没有什么问题。两个bean每次拿都是<strong>全新的</strong>。</p>
<ol start="3">
<li><p>原型依赖单例<br>由于单例，所以原型bean里的单例bean仍然是惟一的。</p>
</li>
<li><p>单例依赖原型</p>
</li>
</ol>
<p>如果希望单例作用域的bean在运行时重复获取原型作用域的bean的新实例，不能将原型作用域的bean依赖项注入到您的单例bean中，因为当Spring容器实例化单例bean并解析并注入其依赖项时，<strong>该注入仅发生一次</strong>。如果在运行时不止一次需要原型bean的新实例，请参见<strong>方法注入</strong>。</p>
<p><a target="_blank" rel="noopener" href="https://song-yang-ji.blog.csdn.net/article/details/109661012">文章末尾就是方法注入的使用</a></p>
<h3 id="1-5-4-使用自定义范围"><a href="#1-5-4-使用自定义范围" class="headerlink" title="1.5.4. 使用自定义范围"></a>1.5.4. 使用自定义范围</h3><p>暂略。。。</p>
<h2 id="1-6-自定义Bean的性质"><a href="#1-6-自定义Bean的性质" class="headerlink" title="1.6 自定义Bean的性质"></a>1.6 自定义Bean的性质</h2><p>Spring框架提供了许多接口，您可以使用这些接口来自定义Bean的性质。本节将它们分为以下几类：</p>
<ol>
<li><p>生命周期回调</p>
</li>
<li><p>ApplicationContextAware 和 BeanNameAware</p>
</li>
<li><p>其他 Aware接口</p>
</li>
</ol>
<h3 id="1-6-1-生命周期回调"><a href="#1-6-1-生命周期回调" class="headerlink" title="1.6.1 生命周期回调"></a>1.6.1 生命周期回调</h3><p>从Spring 2.5开始，您可以至少使用三个方法来控制Bean生命周期行为。</p>
<ol>
<li><p>实现<code>InitializingBean</code>和<code>DisposableBean</code>回调接口</p>
</li>
<li><p>xml里使用<code>init-method</code>和<code>destroy-methodbean</code>定义元数据, 指定回调方法</p>
</li>
<li><p>使用<code>@PostConstruct</code>和<code>@PreDestroy</code>注解</p>
</li>
</ol>
<p>第一种方法，虽然也能达成目的，但是将代码强耦合到Spring，并不被推荐。</p>
<p>第二种方法，使用Spring的xml配置bean的方式完成。</p>
<p>第三种方法，在全注解开发Spring项目的现在，无疑是最佳选择（官方也是这么说的）。</p>
<p><strong>初始化后回调</strong>和<strong>销毁之前回调</strong>的处理是差不多，这里仅仅以初始化回调为例，另一个是一样的。</p>
<h4 id="1-6-1-1-初始化回调"><a href="#1-6-1-1-初始化回调" class="headerlink" title="1.6.1.1 初始化回调"></a>1.6.1.1 初始化回调</h4><ul>
<li>实现 <code>InitializingBean</code>接口<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;exampleInitBean&quot;</span> <span class="attr">class</span>=<span class="string">&quot;examples.AnotherExampleBean&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">AnotherExampleBean</span> <span class="keyword">implements</span> <span class="title class_">InitializingBean</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">afterPropertiesSet</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// do some initialization work</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>使用 bean 的 <code>init-method</code>属性</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;exampleInitBean&quot;</span> <span class="attr">class</span>=<span class="string">&quot;examples.ExampleBean&quot;</span> <span class="attr">init-method</span>=<span class="string">&quot;init&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ExampleBean</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// do some initialization work</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
<li><p>使用 @PostConstruct 注解<br>值得一提的是，这个注解并不是Spring里的，而是javax里的。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">ExampleBean</span> &#123;</span><br><span class="line">	<span class="meta">@PostConstruct</span> </span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">init</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">// do some initialization work</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<h4 id="1-6-1-2-销毁回调"><a href="#1-6-1-2-销毁回调" class="headerlink" title="1.6.1.2 销毁回调"></a>1.6.1.2 销毁回调</h4><p>与上面几乎一样，略。</p>
<h4 id="1-6-1-3-默认初始化和销毁​​方法"><a href="#1-6-1-3-默认初始化和销毁​​方法" class="headerlink" title="1.6.1.3 默认初始化和销毁​​方法"></a>1.6.1.3 默认初始化和销毁​​方法</h4><p>当你需要为很多个，甚至所有的bean去设置初始化或销毁方法的时候，你可以直接为他们设置一个默认的公共的回调方法。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">default-init-method</span>=<span class="string">&quot;init&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;blogService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.something.DefaultBlogService&quot;</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;userService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.something.DefaultUserService&quot;</span>/&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 可以覆盖掉默认的 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;authorService&quot;</span> <span class="attr">class</span>=<span class="string">&quot;com.something.DefaultAuthorService&quot;</span>  <span class="attr">init-method</span>=<span class="string">&quot;initMethod&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>使用 <code>&lt;beans&gt;</code>的default-init-method 为一系列bean设置回调方法。</p>
<p>你还可以覆盖掉默认的。</p>
<h4 id="1-6-1-4-配置多个回调方法的调用顺序"><a href="#1-6-1-4-配置多个回调方法的调用顺序" class="headerlink" title="1.6.1.4 配置多个回调方法的调用顺序"></a>1.6.1.4 配置多个回调方法的调用顺序</h4><ul>
<li>为同一个bean配置的具有不同初始化方法的调用顺序。</li>
</ul>
<ol>
<li><p>用注解的方法 @PostConstruct</p>
</li>
<li><p>由InitializingBean回调接口定义的afterPropertiesSet()</p>
</li>
<li><p>定制配置的init()方法</p>
</li>
</ol>
<p>销毁方法的调用顺序相同：</p>
<ol>
<li><p>用注释的方法 @PreDestroy</p>
</li>
<li><p>由DisposableBean回调接口定义的destroy()</p>
</li>
<li><p>定制配置的destroy()方法</p>
</li>
</ol>
<h4 id="1-6-1-5-Lifecycle接口"><a href="#1-6-1-5-Lifecycle接口" class="headerlink" title="1.6.1.5 Lifecycle接口"></a>1.6.1.5 Lifecycle接口</h4><p>暂略。</p>
<h3 id="1-6-2-ApplicationContextAware-接口"><a href="#1-6-2-ApplicationContextAware-接口" class="headerlink" title="1.6.2 ApplicationContextAware 接口"></a>1.6.2 ApplicationContextAware 接口</h3><p>以前，我们都是用 <code>ApplicationContext</code>去获取Bean（按类型、按bean的名字也罢）。<br>但是bean怎么拿到上下文，进而拿到其他的bean呢？<br>这个接口的出现终于解释了这个问题。</p>
<p>当 <code>ApplicationContext</code> 创建一个实现<code>ApplicationContextAware</code>接口的对象实例时，该实例将获得对<code>ApplicationContext</code>上下文的引用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">BeanImplApplicationContextAware</span> <span class="keyword">implements</span> <span class="title class_">ApplicationContextAware</span> &#123;</span><br><span class="line"></span><br><span class="line">    ApplicationContext context;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 这个方法会由 Spring 自动调用，并传入上下文，</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">setApplicationContext</span><span class="params">(ApplicationContext applicationContext)</span> <span class="keyword">throws</span> BeansException &#123;</span><br><span class="line">        context = applicationContext;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">showBean</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">ExampleBean</span> <span class="variable">exampleBean</span> <span class="operator">=</span> context.getBean(<span class="string">&quot;exampleBean&quot;</span>,ExampleBean.class);</span><br><span class="line">        System.out.println(<span class="string">&quot;在BeanImplApplicationContextAware里获得了&quot;</span>+exampleBean);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>启动类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Boot</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">ConfigurableApplicationContext</span> <span class="variable">applicationContext</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AnnotationConfigApplicationContext</span>(<span class="string">&quot;life_cycle&quot;</span>);</span><br><span class="line">        applicationContext.getBean(BeanImplApplicationContextAware.class).showBean();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-6-3-其他-Aware-接口"><a href="#1-6-3-其他-Aware-接口" class="headerlink" title="1.6.3 其他 Aware 接口"></a>1.6.3 其他 Aware 接口</h3><p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-aware">官方文档的1.6.3</a></p>
<p><strong>必须要指明的一点的是，使用这些接口会将你的代码与Spring API绑定在一起，并且不遵循“控制反转”风格</strong>。</p>
<p>因此，只有在你确实需要编写一些基础bean，而他们确实需要访问 <strong>上下文容器时</strong>，才推荐使用这些接口。（总之，一般不用就拿ApplicationContextAware接口为例，我们完全可以使用自动装配AutoWire来代替它。）</p>
<blockquote>
<p>参考资料</p>
<p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/current-SNAPSHOT/reference/html/core.html#spring-core">Spring官方文档</a></p>
<p><a target="_blank" rel="noopener" href="https://docs.spring.io/spring-framework/docs/">doc index</a></p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Spring%E6%A0%B8%E5%BF%83/" rel="tag"># Spring核心</a>
              <a href="/tags/JavaEE/" rel="tag"># JavaEE</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/07/01/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B01%20%20%E2%80%94%E2%80%94%20%20IOC%E5%AE%B9%E5%99%A8%20I%20%EF%BC%88IOC%E5%AE%B9%E5%99%A8%E3%80%81DI%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5%EF%BC%89/" rel="prev" title="Spring 学习笔记1  ——  IOC容器 I （IOC容器、DI依赖注入）">
                  <i class="fa fa-chevron-left"></i> Spring 学习笔记1  ——  IOC容器 I （IOC容器、DI依赖注入）
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/07/10/Spring%20%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B03%20%E2%80%94%E2%80%94%20IOC%E5%AE%B9%E5%99%A8%203%20(%E4%BD%BF%E7%94%A8%E6%B3%A8%E8%A7%A3%E9%85%8D%E7%BD%AEIOC%E5%AE%B9%E5%99%A8)/" rel="next" title="Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器)">
                  Spring 学习笔记3 —— IOC容器 3 (使用注解配置IOC容器) <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
